package com.qwt.part_time_api.service.impl;


import com.qwt.part_time_api.service.RoleService;
import com.qwt.part_time_api.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 君子慎独
 * 登录的实现 因为使用sceurity所以没有自己实现登录api
 * 但是还是调用 login  参数为username password
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * //自定义的登录逻辑
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户登录");
        if (username == null || "".equals(username)) {
            log.info("账号不能为空");
            throw new RuntimeException("账号不能为空");
        }

        com.qwt.part_time_api.pojo.User user = userService.findUserInfoByUserName(username);

        //根据用户名去数据库进行查询，如不存在则抛出异常
        if (user == null) {
            log.info("用户不存在或账号错误");
            throw new UsernameNotFoundException("用户不存在或账号错误");
        }

        // 用于存放用户对应的角色
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 获取用户对应的角色
        String role = roleService.findRoleNameByAccount(user.getAccount());

        // 对角色授权
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role);

        // 添加
        authorities.add(simpleGrantedAuthority);

        // 将 用户名 - 密码 - 角色 传给security 用于验证和认证
        // 只需要将正确密码传过去 security 会自动对前端传的密码就行对比
        return new User(username, user.getPassword(), authorities);
    }
}


